package com.util.excel;

import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.LinkedList;
import java.util.List;

/**
 * @Description: 竖向合并单元格
 * @Author: hechaobo
 * @Date: 2024/3/7
 **/
public class MergeColHandler implements SheetWriteHandler {
    int col;//下标
    List<int[]> rows;//记录需要合并的行区间

    /**
     * @param col 下标
     * @param list 列数据
     */
    public MergeColHandler(int col, List<String> list){
        this.col=col;
        //i上一个不相等，j当前位置
        int i=0,j=0;
        rows=new LinkedList<>();
        String pre=list.get(0);
        for (String s : list) {
            if(!s.equals(pre)) {
                if(i!=j-1)
                rows.add(new int[]{i,j-1});
                i=j;
            }
            pre=s;
            j++;
        }
        if(i!=j-1) rows.add(new int[]{i,j-1});
    }
    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        Sheet sheet = writeSheetHolder.getSheet();
        for (int[] row : rows) {
            sheet.addMergedRegion(new CellRangeAddress(row[0],row[1],col,col));
        }
    }
}
